import { Logger } from "../../../common/log/Logger";
import { InjectableObject, PresenterOptions } from "../../../inject";
import { INJECT_PRESENT_LIST_TAG } from "../../../inject/typed/injector-typed";
import { BasePresenter } from "../../base/BasePresenter";
import { IBaseView } from "../../base/IBaseView";

export interface IBaseViewProxy {
    injectPresenters(): void;
    detachPresenters(): void;
}

export default class BaseViewMvpProxy extends InjectableObject implements IBaseViewProxy {
    private _view: IBaseView;
    private _presenters: BasePresenter<any>[];

    constructor(view: IBaseView) {
        super();
        this._view = view;
        this._presenters = [];
    }

    public injectPresenters(): void {
        // throw new Error("Method not implemented.");
        let PresentList = Reflect.get(this._view, INJECT_PRESENT_LIST_TAG);

        if (PresentList) {
            PresentList.forEach((element: PresenterOptions) => {
                /**
                 * Injectable修饰的类，已注入到注册器
                 * 否则，不在注入器中
                 */
                let presenter: BasePresenter<any> = this.injector.getInstance(element.propertyType.name);
                if (!presenter)
                    presenter = this.injector.instantiateOf(element.propertyType);

                this._view[element.propertyName] = presenter;
                this._presenters.push(presenter);

                Logger.debug("inject presenter: ", element.propertyName)
                presenter.attach(this._view);

            });
        }
    }

    public detachPresenters(): void {
        this._presenters.forEach(function (p) {
            p.detach();
        });

        this._presenters.splice(0, this._presenters.length);
    }
}